import os
from flask import Flask, render_template, request, g, current_app
import json
from threading import Thread
import serial
from flask_cors import CORS
from loguru import logger

news_read = True
news_content = {}

serial_port = "/dev/ttyUSB0"
ser = serial.Serial(serial_port, 115200)

class Dto():
    def __init__(self, msg, item):
        self.msg = msg
        self.item = item

class Thing():
    def __init__(self, id, name, location):
        self.id = id
        self.name = name
        self.lacation = location

def read_from_port(ser):
    buffer = ""
    while True:
        second = False
        while ser.in_waiting != 0:
            reading = ser.read(ser.in_waiting).decode()
            # 找到头找到尾
            if reading.find("{") != -1 and reading.find("}") != -1:
                buffer = reading
                second = False
            # 找到头找不到尾
            elif reading.find("{") != -1 and reading.find("}") == -1:
                buffer = reading
                second = True
            # 找不到头找到尾
            elif reading.find("{") == -1 and reading.find("}") != -1:
                buffer = buffer + reading
                second = False

            if not second:
                print(buffer)
                handleMsg(buffer)
                buffer = ""
            else:
                pass

def create_app(test_config=None):
    global ser
    app = Flask(__name__, instance_relative_config=True)

    ser_thread = Thread(target=read_from_port, args=(ser,))
    ser_thread.start()

    CORS(app)
    return app

app = create_app()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/news')
def getNews():
    global news_content
    data = ""
    if news_content != "":
        data = news_content
        print(news_content)
    else:
        data = Dto(None, None).__dict__
    response = app.response_class(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )
    news_content = ""
    return response

def handleMsg(msg):
    global news_content
    data = json.loads(msg)
    msg = data['msg']
    if msg == "rfid":
        # RFID
        thing = Thing(data['id'], data['name'], -1).__dict__
        news_content = Dto("rfid", thing).__dict__
    elif msg == "diff":
        # 分拣
        thing = Thing(data['id'], data['name'], str(data['loc'])).__dict__
        news_content = Dto("diff", thing).__dict__
    elif msg == "cap":
        # 入库
        thing = Thing(data['id'], data['name'], str(data['loc'])).__dict__
        news_content = Dto("cap", thing).__dict__
    else:
        pass
